$(document).ready(function(){
	var currentPage = 0;
	var pageSize = 10;
	var token = $.zui.store.get("token");
	var userId = $.zui.store.get("userId");
	
	//用于分页查询
	var queryPageListFun = function(){
		var queryUrl = adminQueryUrl+adminUserService+queryPageListMethod;
		console.log('url2='+queryUrl+",toke="+token+",userId="+userId);
		var param='';
		if ($("#queryUserName").val()!=''){
			param += "&queryUserName="+$("#queryUserName").val()
		}
		if ($("#queryUserState").val()!=''){
			param += "&queryUserState="+$("#queryUserState").val()
		}
		if ($("#queryUserNameLike").val()!=''){
			param += "&queryUserNameLike="+$("#queryUserNameLike").val()
		}
		
		if (currentPage>0){
			param += "&currentPage="+(currentPage-1);
		}
		param += "&pageSize="+pageSize;
		param += "&excludeUserId="+userId;
		$.ajax({
			url:queryUrl,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token:'"+token+"'");
				xhr.setRequestHeader("userId:'"+userId+"'");
			},
			headers:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				console.log('data2='+data);
				$('#listDataGrid').empty();
				$('#listDataGrid').data('zui.datagrid',null);
				$('#listPager').empty();
				$('#listPager').data('zui.pager',null);
				if (data.success == '1'){
					
					//获取用户状态
					$.each(data.statusList, function(i, item){  
						$("#queryUserState").append("<option value='"+item.key_value+"'>"+item.key_name+"</option>");
					}); 
					if (data.pageTotal > 0){
						$('#listDataGrid').datagrid({
							checkable:true,
					        checkByClickRow: true,
						    dataSource: {
						        cols:[
						        	{name: 'User_ID', label: '1', width: 1},
						            {name: 'LoginName', label: '用户名', width: 134},
						            {name: 'trueName', label: '姓名', width: 109},
						            {name: 'AgeUserStatus', label: '用户状态', width: 109},
						            {name: 'Mobile', label: '手机号码', width: 109},
						            {name: 'Opr_Date', label: '操作时间', width: -1},//-1用于自适应宽度
						            {name: 'Sex', label: '性别', hidden:true},
						            ],
						        cache:false,
						        array:data.pageList
						    }
						});
						//获取分页
						$('#listPager').pager({
						    page: data.currentPage,
						    recTotal: data.pageTotal,
						    recPerPage:pageSize,
						    elements:['first_icon', 'prev_icon', 'pages', 'next_icon', 'last_icon', 'total_text','size_menu','goto'],
						    pageSizeOptions:[10,20,30,50,100]
						});
					}
					else {
						$("#listDataGrid").html("<center>查无数据</center>");
					}
				}
				else {
					$("#listDataGrid").html("查无数据");
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	};
	queryPageListFun();
	//监听分页，修改当前页，条数
	$('#listPager').on('onPageChange', function(e, state, oldState) {
		currentPage = state.page;
		pageSize = state.recPerPage;
		console.log('currentPage='+currentPage+",pageSize="+pageSize);
		queryPageListFun();
	});
	//搜索
	$("#searchBtn").click(function(){
		queryPageListFun();
	});
	//初始化添加
	$("#addBtn").click(function(){
		$("#addForm")[0].reset();
		var url = adminQueryUrl + adminUserService+initUserAddMethod;
	    var param = "";
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token:'"+token+"'");
				xhr.setRequestHeader("userId:'"+userId+"'");
			},
			headers:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				console.log('data='+data);
				if (data.success=='1'){
				   //性别
					$("#addUserSex").empty()
					$.each(data.dicsList, function(i, item){ 
						if(item.dics_code == 'Sex'){
							$("#addUserSex").append("<option value='"+item.key_value+"'>"+item.key_name+"</option>");
						   }
						}); 
					//所属角色
					$("#addUserRole").empty()
					$.each(data.roleInfoList, function(i, item){ 
							$("#addUserRole").append("<option value='"+item.Role_ID+"'>"+item.RoleName+"</option>");   
						}); 
					//所属机构
					$("#addUserOrp").empty()
					$.each(data.orgInfoList, function(i, item){ 
							$("#addUserOrp").append("<option value='"+item.Org_ID+"'>"+item.Org_Name+"</option>");
						}); 
					//所属地区
					$("#addUserArea").empty()
					$.each(data.areaInfoList, function(i, item){ 
							$("#addUserArea").append("<option value='"+item.AREA_ID+"'>"+item.areaName+"</option>");
						}); 
					//设置隐藏的默认密码
					$("#defaultPwd").empty();
					$.each(data.dicdList, function(i, item){
					    $("#defaultPwd").val(item.key_name);
					});
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	});
	//添加保存
	$("#addSave").click(function(){
		var validLoginNameUrl = adminQueryUrl + adminUserService + validLoginName;
		$("#addForm").validate({
			rules:{
				addTrueName:{
					"required":true
				},
				addUserName:{
					"required":true,
					"remote":{
						url:validLoginNameUrl,
						type:'get',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token",token);
							xhr.setRequestHeader("userId",userId);
						},
						headers:{'token':token,'userId':userId},
						dataType:'json',
						data:{
							'addUserName':function(){
								return $("#addUserName").val();
							},
						}
					}
				},
				addUserRole:{
					"required":true
				},
				addUserOrp:{
					"required":true
				},
				addUserArea:{
					"required":true
				},
				addUserMobile:{
					"required":true
				}
				
			},
			messages:{
				addUserName:{
					"remote":"用户名称已经存在"
				}
			},
			errorPlacement:function(error,element){
				error.appendTo(element.parent().parent());
			},
			submitHandler:function(form){
				$.ajax({
					url:adminQueryUrl + adminUserService + addMethod,
					type:'post',
					dataType:'JSON',
					beforeSend:function(xhr){//设置请求头信息
						xhr.setRequestHeader("token:'"+token+"'");
						xhr.setRequestHeader("userId:'"+userId+"'");
					},
					headers:{'token':token,'userId':userId},
					data:$(form).serialize(),
					success:function(data){
						console.log('data='+data);
						if (data.success == '1') {
		                	new $.zui.Messager('添加成功!', {
		    				    type: 'success',
		    				    placement:'center'
		    				}).show();
		                	$('#addModal').modal('hide', 'fit');
		                	queryPageListFun();
		                }
		                else{
		                	new $.zui.Messager(data.msg, {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
		                }
					},
					error:function(e){
						new $.zui.Messager('系统繁忙,请稍候再试!', {
	    				    type: 'warning',
	    				    placement:'center'
	    				}).show();
					}
				});
			}
		});
	});
	//初始化修改
	$("#updateBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$("#updateForm")[0].reset();
			$("#updateUserId").val(selectedItems[0].User_ID);
			var url = adminQueryUrl + adminUserService+initUpdateMethod;
			var param = 'updateUserId='+selectedItems[0].User_ID;//请求到列表页面
			console.log('param='+param);
			$.ajax({
				url:url,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){//设置请求头信息
					xhr.setRequestHeader("token:'"+token+"'");
					xhr.setRequestHeader("userId:'"+userId+"'");
				},
				headers:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('data='+data);
					if (data.success=='1'){
						$('#updateModal').modal('show', 'fit');
						//$("#updateUserId").val(data.userMap.userID);
						$("#updateUserName").val(data.userMap.loginName);
						$("#updateTrueName").val(data.userMap.trueName);
						$("#updateUserPasswd").val(data.userMap.passwd);
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
			});
		}
	});

	//修改保存
	$("#updateSave").click(function(){
		$("#updateForm").validate({
			rules:{
				updateUserName:{
					"required":true
				},
				updateTrueName:{
					"required":true
				},
				updateUserPasswd:{
					"required":true
				}
			},
			errorPlacement:function(error,element){
				error.appendTo(element.parent().parent());
			},
			submitHandler:function(form){
					$.ajax({
					url:adminQueryUrl + adminUserService+updateMethod,
					type:'post',
					dataType:'JSON',
					beforeSend:function(xhr){//设置请求头信息
						xhr.setRequestHeader("token",token);
						xhr.setRequestHeader("userId",userId);
					},
					headers:{'token':token,'userId':userId},
					data:$(form).serialize(),
					success:function(data){
						console.log('data='+data);
						if (data.success == '1') {
		                	new $.zui.Messager('修改成功!', {
		                		type: 'success',
		    				    placement:'center'
		    				}).show();
		                	$('#updateModal').modal('hide', 'fit');
		                	queryPageListFun();
		                }
		                else{
		                	new $.zui.Messager(data.msg, {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
		                }
					},
					error:function(e){
						new $.zui.Messager('系统繁忙,请稍候再试!', {
	    				    type: 'warning',
	    				    placement:'center'
	    				}).show();
					}
				});
			}
		});
	});
	//显示删除确认框
	$("#deleteBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$('#deleteModal').modal('show', 'fit');
		}
	});
	//删除地区
	$("#deleteUserBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		var url = adminQueryUrl + adminUserService+deleteMethod;
		var param = 'deleteUserId='+selectedItems[0].User_ID;//请求到列表页面
		console.log('param2='+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token:'"+token+"'");
				xhr.setRequestHeader("userId:'"+userId+"'");
			},
			headers:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				console.log('data='+data);
				$('#deleteModal').modal('hide', 'fit');
				if (data.success=='1'){
	                	new $.zui.Messager('删除成功!', {
	    				    type: 'success',
	    				    placement:'center'
	    				}).show();
	                	queryPageListFun();
				}
                else{
                	new $.zui.Messager(data.msg, {
    				    type: 'warning',
    				    placement:'center'
    				}).show();
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	});
	//初始化详情
	$("#detailBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要查看的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要查看的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$("#detailForm")[0].reset();
			var url = adminQueryUrl + adminUserService+detailMethod;
			var param = 'userId='+selectedItems[0].User_ID;//请求到列表页面
			console.log('param='+param);
			$.ajax({
				url:url,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){//设置请求头信息
					xhr.setRequestHeader("token:'"+token+"'");
					xhr.setRequestHeader("userId:'"+userId+"'");
				},
				headers:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('data='+data);
					if (data.success=='1'){
						$('#detailModal').modal('show', 'fit');
						$("#TrueName").html(selectedItems[0].trueName);
						$("#UserName").html(selectedItems[0].LoginName);
						$("#UserState").html(selectedItems[0].AgeUserStatus);
						$("#UserOrp").html(data.userMap.Org_Code);
						$("#UserArea").html(data.userMap.Area_Code);
						$("#UserPwd").html(data.userMap.passwd);
						$("#UserSex").html(selectedItems[0].Sex);
						$("#UserMobile").html(data.userMap.Mobile);
						$("#UserEmail").html(data.userMap.Email);
						$("#UserQQ").html(data.userMap.Qq);
						$("#UserWeixin").html(data.userMap.Weixin);
						$("#UserAddress").html(data.userMap.Address);
						$("#OprId").html(data.userMap.Opr_id);
						$("#OprDate").html(data.userMap.Opr_Date);
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
			});
		}
	});
	//显示重置密码框
	$("#resetBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要重置的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要重置的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$('#resetModal').modal('show', 'fit');
		}
	});
	//重置密码
	$("#resetUserBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		var url = adminQueryUrl + adminUserService+resetMethod;
		var param = 'resetUserId='+selectedItems[0].User_ID;//请求到列表页面
		console.log('param2='+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token:'"+token+"'");
				xhr.setRequestHeader("userId:'"+userId+"'");
			},
			headers:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				console.log('data='+data);
				$('#resetModal').modal('hide', 'fit');
				if (data.success=='1'){
	                	new $.zui.Messager('重置成功!', {
	    				    type: 'success',
	    				    placement:'center'
	    				}).show();
	                	queryPageListFun();
				}
                else{
                	new $.zui.Messager(data.msg, {
    				    type: 'warning',
    				    placement:'center'
    				}).show();
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	});
});
